<?php

namespace common\behavior\CommonMessagePushing;

use Webman\Stomp\Client;

/**
 * 任务分配行为 消息通知
 */
class TaskAssignV2Behavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        if (($params['type'] ?? '') != 'task_assign_v2') {
            return;
        }

        $taskAssignList = [];
        foreach ($params['task_assign_list'] as $taskAssignInfo) {
            $taskAssignInfo['receiver'] = $taskAssignInfo['receiver'] ?? [];
            $taskAssignInfo['receiver_cc'] = $taskAssignInfo['receiver_cc'] ?? [];
            if (!isset($taskAssignList[$taskAssignInfo['task_id']])) {
                $taskAssignList[$taskAssignInfo['task_id']] = $taskAssignInfo;
            } else {
                array_push($taskAssignList[$taskAssignInfo['task_id']]['receiver'], ...$taskAssignInfo['receiver']);
                array_push($taskAssignList[$taskAssignInfo['task_id']]['receiver_cc'], ...$taskAssignInfo['receiver_cc']);
            }
        }
        foreach ($taskAssignList as $taskAssignInfo) {
            $data = [
                'source_user_id' => $params['user_id'],
                'time' => $params['time'],
                'source_id' => $taskAssignInfo['task_id'],
                'source_module_code' => 'task',
                'category' => 'task_assign',
                'receiver' => $taskAssignInfo['receiver'] ?? [],
                'receiver_cc' => $taskAssignInfo['receiver_cc'] ?? [],
            ];
            try {
                trace("common task assign push behavior" . request()->getUnionUserId(), 'DEBUG');
                Client::send('common_message_pushing', build_queue_data_with_xu($data));
            } catch (\Throwable $e) {
                trace(format_exception_info($e), 'ERR');
            }
        }
        return;
    }
}
